<template>
	<view class="container">
		<!-- Status Bar Height Placeholder -->
		<!-- Navigation Bar -->
		<view class="nav-bar">
			<view class="back-btn" @click="goBack">
				<text class="cuIcon-back"></text>
			</view>
			<view class="nav-title">确认租用</view>
			<view class="placeholder"></view>
		</view>

		<!-- Station Info -->
		<view class="station-section">
			<view class="section-title">溜娃车站点</view>
			<view class="station-card" style="position: relative;">
				<view class="station-icon">
					<text class="cuIcon-location"></text>
				</view>
				<view class="station-info" style="display: flex;">
					<view>
						<view class="station-title">{{ station_title }}</view>
						<view class="station-address">{{ alias }}</view>
					</view>
					<view class="station-status" style="position: absolute; right: 5px; top: 10px;" :class="{ 'active': station_title || alias }">
						{{ station_title || alias ? '可租用' : '不可租用' }}
					</view>
				</view>
			</view>
		</view>

		<!-- Package Selection -->
		<view class="package-section">
			<view class="section-title">使用说明</view>
			<view class="payment-info">
				<view class="payment-row">
					<text>预付款：</text>
					<text class="price-symbol">￥</text>
					<text class="price-value">{{depositAmount}}</text>
				</view>
			</view>
			<br>
			<view class="instructions-content">
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">童车仪限3周岁以上、30KG以下的一名儿童使用;</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">童车仅限乘坐使用，严禁推行玩耍;</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">请勿在台阶、扶梯、斜坡、不平路面和交通公路使用</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">儿童须在监护人看护下使用童车,使用期间,监护人切记扶稳手柄</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">请您在规定时间内借还童车,场地营业结束后无法租还童车,否则会影响您的计费和押金退还</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">请勿将童车带离场地(商场或景区),否则视为违规使用、用户须承担相应责任</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">如果用车不满足免押条件,用车前先支付押金,还车后即刻退还押金余额。如您有疑问可随时联系客服</text>
				</view>
				<view class="instruction-item">
					<text class="instruction-dot"></text>
					<text class="instruction-text">前五分钟用车免费,超过五分钟正常计费。半小时{{priceHour/2}}元，不足半小时按半小时计算</text>
				</view>
			</view>
		</view>

		<!-- Payment Method -->
		<view class="payment-section">
			<view class="section-title">支付方式</view>
			<view class="payment-list">
				<view class="payment-item" v-for="(method, index) in paymentMethods" :key="index"
					:class="{ 'selected': selectedPayment === index }" @click="selectPayment(index)">
					<view class="payment-icon">
						<image src="../../static/wx.png" mode=""></image>
					</view>
					<view class="payment-name">{{ method.name }}</view>
					<view class="payment-check">
						<text class="cuIcon-check" v-if="selectedPayment === index"></text>
					</view>
				</view>
			</view>
		</view>


		<!-- Bottom Bar -->
		<view class="bottom-bar">
			<view class="total-price">
				<text>总计支付: </text>
				<text class="price-symbol">￥</text>
				<text class="price-value">{{ depositAmount}}</text>
			</view>
			<view class="pay-btn" @click="payNow">立即支付</view>
		</view>
	</view>
</template>

<script>
	import {
		WX_CONFIG,
		API_CONFIG,
		STORAGE_KEYS
	} from '@/config/constants.js';

	export default {
		data() {
			return {
				statusBarHeight: 20, // 状态栏高度
				stationCode: '', // 站点编码，从路由参数获取
				station: { // 站点详情数据
					code: '',
					title: '',
					state: '',
					geographic: {
						address: '',
						latitude: 0,
						longitude: 0
					}
				},
				depositAmount: 0, // 押金金额
				priceHour: 0,
				packages: [],
				paymentMethods: [ // 支付方式列表
					{
						name: '微信支付',
						icon: '/static/payment/wechat.png'
					}
				],
				selectedPayment: 0, // 默认选中微信支付，
				timer: "",
				payment: "", //支付信息，
				isPaying: false, //支付锁,
				station_title: '',
				alias: "",
				option: "",
				order: ""
			};
		},
		onLoad(options) {
			this.getStatusBarHeight(); // 获取状态栏高度
			this.stationCode = options.stationCode; // 从路由参数获取站点编码
			this.getStationInfo(); // 获取站点详情
			this.getPriceInfo()
			// 获取路由传参
			if (options) {
				this.station_title = options.station_title
				this.alias = options.alias
				this.option = options
			}
			console.log(options);
		},
		methods: {
			// 获取状态栏高度，用于自适应不同设备
			getStatusBarHeight() {
				const systemInfo = uni.getSystemInfoSync();
				this.statusBarHeight = systemInfo.statusBarHeight;
			},

			// 根据站点编码获取站点详细信息
			getStationInfo() {

			},

			// 选择套餐
			selectPackage(index) {
				this.selectedPackage = index;
			},

			// 选择支付方式
			selectPayment(index) {
				this.selectedPayment = index;
			},



			// 立即支付按钮点击事件
			async payNow() {
				if (this.isPaying) return; // 防止重复点击
				this.isPaying = true; // 锁定按钮
				try {
					const data = await this.createOrder();
					if (data.code == '400') {
						uni.showToast({
							title: data.msg,
							icon: 'error'
						})
						return
					}
					this.order = data.data.data;
					
					uni.setStorageSync("password",data.data.password)
					if (data) {
						await this.wechatPayService(data.data.payment);
					}
				} catch (err) {
					console.error('支付流程异常:', err);
				} finally {
					this.isPaying = false; // 解锁按钮
				}
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 创建订单
			async createOrder() {
				// 获取当前操作的用户token
				const token = uni.getStorageSync(STORAGE_KEYS.token)
				try {
					const res = await uni.request({
						url: API_CONFIG.baseUrl + "/babyCar.Order/create?token=" + token,
						method: "POST",
						header: {
							'content-type': 'application/json'
						},
						data: {
							"station_id": this.option.station_id,
							"layout_id": this.option.layout_id,
							"pile_hw_code": this.option.pile_hw_code,
							"wheel_hw_code": this.option.wheel_hw_code,
							"fee": this.depositAmount, // 使用费用
						}
					})
					console.log(res[1].data.data);
					return res[1].data
				} catch (err) {
					uni.showToast({
						title:"支付异常",
						icon:"error"
					})
					console.error(err);
				}
			},
			// 调用微信支付接口
			wechatPayService(data) {
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: data.timeStamp,
					nonceStr: data.nonceStr,
					package: data.package,
					signType: data.signType,
					paySign: data.paySign,
					success: (res) => {
						if (res.errMsg === "requestPayment:ok") {
							uni.showToast({
								title: '支付成功',
								icon: 'success'
							});
							//更新订单状态
							this.updateOrderStatus(this.order)
							// 支付成功后直接调用后端开锁接口
							this.unlock()
						}
					},
					fail: (err) => {
						console.error("微信接口服务调用失败：" + err)
						uni.showToast({
							title: '取消支付或支付异常',
							icon: 'error'
						})
					}
				})
			},
			
			// 更新订单状态
			async updateOrderStatus(order) {
				const token = uni.getStorageSync("token");
				await uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Order/updateStatus?order_id=" + order.order_id +
						"&status=paid",
					header: {
						"Authorization": token
					},
					method: 'POST',
					success: (res) => {
						console.log(res);
						if (res.data.code == 1) {
							uni.navigateTo({
								url: "/mine-page/order/order_detail?id=" + this.order.order_id
							})
						}
					},
					fail: (err) => {
						console.error("错误", err);
					}  
				});
			},
			// 获取预付款以及每小时金额
			getPriceInfo() {
				uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Price/list",
					method: "GET",
					success: (res) => {
						res.data.data.forEach(item => {
							if (item.package_id === 1) {
								this.priceHour = parseFloat(item.price).toFixed(2)
							} else if (item.package_id === 2) {
								this.depositAmount = parseFloat(item.price).toFixed(2)
							}
						})
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			// 硬件开锁
			unlock(){
				uni.request({
					url:API_CONFIG.baseUrl+"/babyCar.pile/unlock",
					method:"POST",
					data:JSON.stringify({
						station_id:this.option.station_id,
						pile_idx:this.option.pile_idx,
						num:this.option.num
					}),
					success: (res) => {
						console.log(res);
					},
					fail: (err) => {
						console.error(err)
					}
				})
			}
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #F8F8F8;
		padding-bottom: 50px;
	}

	.nav-bar {
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 44px;
		background-color: #FFFFFF;
		border-bottom: 1px solid #EEEEEE;
	}

	.back-btn {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 18px;
		font-weight: bold;
	}

	.placeholder {
		width: 44px;
	}

	.station-section,
	.package-section,
	.payment-section,
	.instructions-section {
		margin-top: 10px;
		background-color: #FFFFFF;
		padding: 15px;
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333333;
		margin-bottom: 15px;
	}

	.station-card {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 15px;
		background-color: #F8F8F8;
		border-radius: 8px;
	}

	.station-icon {
		width: 40px;
		height: 40px;
		background-color: #FFD000;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #333333;
		font-size: 20px;
	}

	.station-info {
		flex: 1;
		margin-left: 10px;
	}

	.station-title {
		font-size: 16px;
		color: #333333;
		margin-bottom: 5px;
	}

	.station-address {
		font-size: 14px;
		color: #999999;
		margin-bottom: 5px;
	}

	.station-status {
		font-size: 14px;
		color: #FF0000;
	}

	.station-status.active {
		color: #00AA00;
	}

	/* 修改为田字格布局 */
	.package-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		grid-template-rows: 1fr 1fr;
		gap: 15px;
	}

	.package-item {
		height: 100px;
		background-color: #F8F8F8;
		border-radius: 8px;
		padding: 15px;
		position: relative;
		border: 1px solid transparent;
	}

	.package-item.selected {
		background-color: #FFF9E6;
		border-color: #FFD000;
	}

	.package-duration {
		font-size: 16px;
		color: #333333;
		margin-bottom: 10px;
	}

	.package-price {
		font-size: 14px;
		color: #FF5000;
	}

	.price-symbol {
		font-size: 14px;
	}

	.price-value {
		font-size: 20px;
		font-weight: bold;
	}

	.package-original {
		font-size: 12px;
		color: #999999;
		text-decoration: line-through;
		margin-top: 5px;
	}

	.package-tag {
		position: absolute;
		top: 0;
		right: 0;
		background-color: #FF5000;
		color: #FFFFFF;
		font-size: 12px;
		padding: 2px 6px;
		border-radius: 0 8px 0 8px;
	}

	.payment-list {
		display: flex;
		flex-direction: column;
	}

	.payment-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		height: 60px;
		border-bottom: 1px solid #F5F5F5;
	}

	.payment-item:last-child {
		border-bottom: none;
	}

	.payment-icon {
		width: 30px;
		height: 30px;
		margin-right: 10px;
	}

	.payment-icon image {
		width: 100%;
		height: 100%;
	}

	.payment-name {
		flex: 1;
		font-size: 16px;
		color: #333333;
	}

	.payment-check {
		width: 20px;
		height: 20px;
		color: #FFD000;
		font-size: 20px;
	}

	.instructions-content {
		display: flex;
		flex-direction: column;
	}

	.instruction-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 10px;
	}

	.instruction-dot {
		width: 6px;
		height: 6px;
		background-color: #999999;
		border-radius: 50%;
		margin-right: 10px;
	}

	.instruction-text {
		font-size: 14px;
		color: #666666;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		background-color: #FFFFFF;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0 15px;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05);
	}

	.total-price {
		flex: 1;
		font-size: 16px;
		color: #333333;
	}

	.pay-btn {
		width: 120px;
		height: 40px;
		background-color: #FFD000;
		color: #333333;
		font-size: 16px;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.payment-info {
		background-color: #F8F8F8;
		padding: 15px;
		border-radius: 8px;
	}

	.payment-row {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
		font-size: 16px;
		color: #333333;
	}

	.payment-row.total {
		margin-top: 15px;
		padding-top: 15px;
		border-top: 1px solid #EEEEEE;
		font-weight: bold;
	}

	.payment-row .price-symbol {
		margin: 0 2px;
	}

	.payment-row .price-value {
		font-size: 18px;
		font-weight: bold;
		color: #FF5000;
	}

	.payment-row.total .price-value {
		font-size: 20px;
	}
</style>